export function RandNum(length) {
  let str = ''
  for (let i = 0; i < length; i++) {
    str += Math.floor(Math.random() * 10)
  }
  return str
}

// 获取随机偶数
function GetRandonEven() {
  const Even = ['0', '2', '4', '6', '8']
  return '' + Even[Math.floor(Math.random() * 5)]
}

// 获取随机奇数
function GetRandonOdd() {
  const Odd = ['1', '3', '5', '7', '9']
  return '' + Odd[Math.floor(Math.random() * 5)]
}

export function GenrateIdCard(options = {
  areaCode: '110101', birthday: '1990-01-01', gender: 'male'
}) {
  const { areaCode, birthday, gender } = options
  const rank = [
    '7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2'
  ]
  const last = [
    '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'
  ]
  // 地区编码加上生日6+8共14位
  let id = areaCode + birthday.replace(/-/g, '')
  // 所在派出所编码2位
  id += RandNum(2)
  // 性别编码，男奇数，女偶数
  if (gender === 'male') {
    id += GetRandonOdd()
  } else if (gender === 'female') {
    id += GetRandonEven()
  } else {
    id += GetRandonOdd()
  }
  // 添加最后一位校验位数
  let sum = 0
  for (let i = 0; i < id.length; i++) {
    sum += id[i] * rank[i]
  }
  id += last[sum % 11]
  return id
}
